#!/bin/bash

echo "Starting incremental sync from source to target..."

# 等待数据库服务启动
echo "Waiting for databases to be ready..."
sleep 10

# 检查源数据库连接
echo "Checking source database connection..."
mongosh --host 192.168.3.3:27027 --username admin --password passwordA --authenticationDatabase admin --eval "db.runCommand('ping')"

if [ $? -ne 0 ]; then
    echo "Error: Cannot connect to source database"
    exit 1
fi

# 检查目标数据库连接
echo "Checking target database connection..."
mongosh --host 192.168.3.3:27020 --username admin --password passwordB --authenticationDatabase admin --eval "db.runCommand('ping')"

if [ $? -ne 0 ]; then
    echo "Error: Cannot connect to target database"
    exit 1
fi

# 获取当前oplog时间戳作为起始点
echo "Getting current oplog timestamp..."
TIMESTAMP=$(mongosh --host 192.168.3.3:27027 --username admin --password passwordA --authenticationDatabase admin --quiet --eval "
  db.getSiblingDB('local').oplog.rs.find().sort({\$natural:-1}).limit(1).forEach(function(doc) {
    print(doc.ts.t + ',' + doc.ts.i);
  });
")

if [ -z "$TIMESTAMP" ]; then
    echo "Error: Cannot get oplog timestamp"
    exit 1
fi

echo "Starting incremental sync from timestamp: $TIMESTAMP"

# 执行增量同步
mongosync \
    --acceptDisclaimer \
    --cluster0 "mongodb://admin:passwordA@192.168.3.3:27027/admin" \
    --cluster1 "mongodb://admin:passwordB@192.168.3.3:27020/admin" \
    --verbosity INFO

echo "Incremental sync completed!" 